<!DOCTYPE html>

<html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript" src="utils.js" charset="UTF-8"></script>
	<script type="text/javascript" src="wskt.js" charset="UTF-8"></script>

	<script type="text/javascript">
        // 重定向日志到页面上，以便调试
        console.log = function(message) {
            if(utils.empty(message)) { return }
            txtlog.value += message + '\r\n';
        };

        let skt;
        
        let eventHandlers = {
            onOpen: function() {
                console.log("连接已建立！");
            },
            onClose: function() {
                console.log("连接已断开！");
            },
            onError: function(message) {
                console.log(message);
            },
            onMessage: function(message) {
                console.log(message.data);
            },
        }
        
        function openws() {
			skt = wskt.open(wsurl.value, eventHandlers);
		}

		// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，
		// 防止连接还没断开就关闭窗口，server端会抛异常。
		window.onbeforeunload = function() {
			if(skt) { skt.close(); skt = null; }
		}
	</script>

	<style>
		* {
			font-family: Consolas;
			font-size: 26px;
		}
		
		#wsurl {
			width: 920px;
		}
	</style>

	<head>
		<title>WebSocket测试</title>
	</head>

	<body>
		<input list='select' id="wsurl" rows="1" cols="64" spellcheck="false" value="ws://localhost:8504/webskt"> </input>
		<br>
		<br>
		<textarea id="text" rows="4" cols="64" spellcheck="false">
{
    "msgType": 10,
    "msgId": 12345678,
    "from": "webCaller1234",
    "token": "token1234",
    "method": "app.getUiObject",
    "params": "{\"oid\":0}"
}
        </textarea>
		<br>
		<button onclick="openws()">建立连接</button>
		<button onclick="skt.send(text.value)">发送消息</button>
		<button onclick="txtlog.value = ''">消除日志</button>
		<button onclick="if(skt) { skt.close(); skt = null; }">关闭连接</button>
		<br>
		<textarea id="txtlog" rows="60" cols="64" readonly="readonly"></textarea>
	</body>

</html>